﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Linq;

namespace CommonLib
{
    public class EntitySession : IDisposable
    {
        private ISession session;

        public EntitySession(ISession session)
        {
            this.session = session;
        }

        public T Create<T>()
            where T : new()
        {
            T t = new T();
            return t;
        }

        public object Create(string entityName)
        {
            return Activator.CreateInstance(Type.GetType(entityName));
        }

        public T Get<T>(object id)
        {
            return session.Get<T>(id);
        }

        public Object Get(string entityName, object id)
        {
            return session.Get(entityName, id);
        }

        public void Add(object entity)
        {
            session.Save(entity);
        }

        public void Delete(object entity)
        {
            session.Delete(entity);
        }

        public void SaveChanges()
        {
            using (ITransaction trans = session.BeginTransaction())
            {
                session.Flush();
                trans.Commit();
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            session.Dispose();
        }

        #endregion

        #region LazyLoading

        public bool IsInitialized(object o)
        {
            return NHibernateUtil.IsInitialized(o);
        }

        public void Initialize(object o)
        {
            NHibernateUtil.Initialize(o);
        }

        #endregion

    }
}
